import random

from libs.base.model import BaseModel


class HomepageModel(BaseModel):

    def __init__(self, handler):
        super(HomepageModel, self).__init__(handler)
        self.handler = handler
        self.data = {}

    async def stat_data(self):
        """
        首页统计数据
        """
        column_graph = [["%s月" % x, random.randint(0, 1000)] for x in range(1, 13)]
        data = {
            "total_data": {
                "a": random.randint(10000, 100000),
                "b": random.randint(1000, 3000),
                "c": random.randint(100, 500),
                "d": random.randint(50, 100)
            },
            "column_graph": column_graph
        }
        return self.set_res_info(0, data=data)


class GlobalDataModel(BaseModel):

    def __init__(self, handler):
        super(GlobalDataModel, self).__init__(handler)
        self.handler = handler
        self.data = {}

    async def get_region(self):
        """
        获取区域数据
        """
        await self.db.select("wx_region", "*")
        data = self.db.fetchall()
        return self.set_res_info(0, data=data)


class AutoCompleteModel(BaseModel):

    def __init__(self, handler):
        super(AutoCompleteModel, self).__init__(handler)
        self.handler = handler
        self.data = {}

    async def get_user(self, opts):
        """
        根据模糊查询, 获取前十条用户信息
        """
        if opts["key"]:
            key_list = [x for x in opts["key"].split(" ") if x]
            keys = "%{name}%".format(name="%".join(key_list))
            sql = '''
                SELECT user_id, name, phone_number
                FROM auth_user
                WHERE name LIKE %s AND data_status=1
                ORDER BY name DESC LIMIT 10
            '''
            await self.db.execute(sql, (keys,))
        else:
            sql = '''
                SELECT user_id, name, phone_number
                FROM auth_user
                WHERE data_status=1
                ORDER BY name DESC LIMIT 10
            '''
            await self.db.execute(sql)
        data_list = self.db.fetchall()
        return self.set_res_info(0, data=data_list)
